package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.GoodsTypeDao;
import com.atguigu.jxc.entity.GoodsType;
import com.atguigu.jxc.entity.Log;
import com.atguigu.jxc.service.GoodsTypeService;
import com.atguigu.jxc.service.LogService;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GoodsTypeServiceImpl implements GoodsTypeService {

    @Autowired
    private LogService logService;

    @Autowired
    private GoodsTypeDao goodsTypeDao;


    @Override
    public String loadGoodsType() {
        List<GoodsType> goodsTypeList = goodsTypeDao.getGoodsType();
        List<Integer> goodsTypeIds = new ArrayList<>();
        for (GoodsType goodsType : goodsTypeList) {
            goodsTypeIds.add(goodsType.getGoodsTypeId());
        }

        logService.save(new Log(Log.SELECT_ACTION, "查询菜单信息"));

        return this.getCheckAllGoodsType(-1,goodsTypeIds).toString();
    }

    /**
     * 递归查询所有菜单
     * @return
     */
    private JsonArray getCheckAllGoodsType(Integer parentId, List<Integer> goodsTypeIds) {
        JsonArray array = this.getCheckGoodsTypeByParentId(parentId,goodsTypeIds);
        for(int i=0;i<array.size();i++){

            JsonObject obj = (JsonObject) array.get(i);

            if(obj.get("state").getAsString().equals("open")){//如果是叶子节点，不再递归

                continue;

            }else{//如果是根节点，继续递归查询

                obj.add("children", this.getCheckAllGoodsType(obj.get("id").getAsInt(),goodsTypeIds));

            }

        }


        return array;
    }

    /**
     * 根据父菜单ID获取所有子菜单
     * @return
     */
    private JsonArray getCheckGoodsTypeByParentId(Integer parentId, List<Integer> goodsTypeIds) {

        JsonArray array = new JsonArray();

        List<GoodsType> goodsTypeList =  goodsTypeDao.getAllGoodsTypeByParentId(parentId);

        for (GoodsType goodsType : goodsTypeList) {

            JsonObject obj = new JsonObject();

            obj.addProperty("id",goodsType.getGoodsTypeId());

            obj.addProperty("text",goodsType.getGoodsTypeName());

            if (goodsType.getGoodsTypeState() == 1){
                obj.addProperty("state","closed");
            }else {
                obj.addProperty("state","open");
            }
            if (goodsTypeIds.contains(goodsType.getGoodsTypeId())){
                obj.addProperty("checked", true);
            }

//        JsonObject attributes = new JsonObject();
            array.add(obj);
        }
        return array;
    }
}